<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import { pie1 } from '@/api/good'
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')

      this.chart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          left: 'center',
          bottom: '10',
          data: ['Industries', 'Technology', 'Forex', 'Gold', 'Forecasts']
        },
        series: [
          {
            name: 'WEEKLY WRITE ARTICLES',
            type: 'pie',
            roseType: 'radius',
            radius: [30, 105],
            center: ['50%', '38%'],
            data: [
              { name: '谷物', value: 32 },
              { name: '水果', value: 24 },
              { name: '豆类', value: 14 },
              { name: '蔬菜', value: 59 }
            ],
            animationEasing: 'cubicInOut',
            animationDuration: 2600
          }
        ]
      })
      this.updateChartData()
    },
    updateChartData() {
      // 发送请求获取新数据
      pie1().then(response => {
        console.log(response.data)
        // 更新图表数据
        this.chart.setOption({
          series: [
            {
              data: [
                { name: '谷物', value: response.data.grains },
                { name: '水果', value: response.data.fruits },
                { name: '豆类', value: response.data.legumes },
                { name: '蔬菜', value: response.data.vegetables }
              ]
            }
          ]
        })
      }).catch(error => {
        console.log('Error fetching options:', error) // 处理错误情况
      })
    }

  }
}
</script>
